<?php

/**
 * BaseController
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

abstract class BaseController extends Zend_Controller_Action {
	
	function init() {
		parent::init();
		$registry = Zend_Registry::getInstance ();
		
		//Zend_Loader::loadClass('Zend_Auth');
		//Zend_Loader::loadClass('Zend_Session_Namespace');
		//Zend_Loader::loadClass('TempMiembrosModel');		
		$this->view->baseUrl = $this->_request->getBaseUrl();
		
		$this->view->dojoBaseUrl = "http://o.aolcdn.com/dojo/1.1.1/";
		//$this->_request->getBaseUrl () + "/dojo-release-1.0.2/"
		//$this->view->dojoUrl = $this->view->dojoBaseUrl . "dojo/dojo.xd.js";
		$this->view->dojoUrl = $this->view->dojoBaseUrl . "dojo/dojo.xd.js.uncompressed.js";
		
		$this->view->title = "Bienvenidos al Registro Nacional de Actividades";
		$this->view->mensajesValidacion = array();
		$usuario = Zend_Auth::getInstance()->getIdentity();
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			//var_dump($usuario);
			//die();
			$this->view->user = $usuario;
			$this->view->role = $usuario->getRoleId(); 
		} else {
			$this->view->role = 'general';
		}
		$rscs = $registry->get ( 'rscs' );
		$this->view->rscs = $rscs;
		$acl = $registry->get ( 'acl' );
		$this->view->acl = $acl;
	}
	
	function verificarSesion() {
		$auth = Zend_Auth::getInstance ();
		if (! $auth->hasIdentity ()) {
			$this->_redirect('auth/login');
		}
	}
	
	// 2. Override the `dispatch` method
	public function dispatch($action) {
		// 3. Get all request parameters
		$params = $this->_getAllParams ();
		
		// 4. Get all action method parameters
		$method_params_array = $this->get_action_params ( $action );
		if (sizeof ( $method_params_array ) == 0) {
			parent::dispatch ( $action );
		} else {
			$data = array ( ); // It will sent to the action
			

			foreach ( $method_params_array as $param ) {
				$name = $param->getName ();
				if ($param->isOptional ()) { // Check whether the parameter is optional
					// If there is no data to send, use the default
					$data [$name] = ! empty ( $params [$name] ) ? $params [$name] : $param->getDefaultValue ();
				} elseif (empty ( $params [$name] )) {
					// The parameter cannot be empty as defined
					throw new Exception ( 'Parameter: ' . $name . ' Cannot be empty' );
				} else {
					$data [$name] = $params [$name];
				}
			}
			
			// 5. Invoke the action and pass the request parameters as actions method parameters, according to their order and names.
			call_user_func_array ( array ($this, $action ), $data );
		}
	
	}
	
	private function get_action_params($action) {
		$classRef = new ReflectionObject ( $this );
		$className = $classRef->getName ();
		$funcRef = new ReflectionMethod ( $className, $action );
		$paramsRef = $funcRef->getParameters ();
		return $paramsRef;
	}
}
